<script>
import {
  TABLE_FIELD_QUARTER, TABLE_FIELD_YEAR,
} from '@/config'
import EnergyTableMixin from '@/components/quarterly-account-table/energy-table-mixin'
import ArrowSelectMixin from '@/components/quarterly-account-table/arrow-select-mixin'
import { uuid } from '@/utils'
import { loadGoalCompletionStatus } from '@/api/enterpriseQuarterlyReport'

const P = '单位产品综合能耗进度节能量目标完成率'
const Q = '产值综合能耗进度节能量目标完成率'
const R = '进度节能量目标完成情况说明'
export default {
  name: 'progress-energy-saving-target-completion-table',
  mixins: [EnergyTableMixin, ArrowSelectMixin],
  created () {
    this.loadList = loadGoalCompletionStatus
  },
  data () {
    return {
      description: {
        key: 'oneYear',
        value: '',
        editable: !this.readonly
      },
      // 表序号
      seriesNo: '表1-4',
    }
  },
  computed: {
    calc () {
      const keys = ['oneYear', 'twoYear', 'threeYear', 'fourYear', 'fiveYear']
      const prefix = [P, Q]
      const lists = this.lists
      // 进度节能量目标
      const t1 = lists[0]?.data
      // 单位产品综合能耗实际完成进度节能量
      const t2 = lists[1]?.data
      // 产值综合能耗实际完成进度节能量
      const t3 = lists[2]?.data

      if (!t1 || !t2 || !t3) return {}
      const calculate = (a, b) => {
        const n = +((100 * (+a) / (+b)).toFixed(2))
        return Number.isFinite(n) ? n : ''
      }
      // 单位产品综合能耗进度节能量目标完成率 =
      // (单位产品综合能耗实际完成节能量 ÷ 进度节能量目标) × 100%

      // 产值综合能耗进度节能量目标完成率 =
      // (产值综合能耗实际完成节能量 ÷ 进度节能量目标) × 100%
      const obj = {}
      for (const r of prefix) {
        for (const k of keys) {
          const key = r + k
          const v1 = (r === P ? t2 : t3).find(vv => vv.key === k)
          const v2 = t1.find(vv => vv.key === k)
          obj[key] = calculate(v1?.value, v2?.value)
        }
      }
      return obj
    },
  },
  methods: {
    transfer (lists) {
      return lists.map(v => {
        const data = this.flattenColumns.map(vv => {
          const key = vv.prop
          const value = String(v[key] || '')
          let editable = true
          let calculable
          let calculationKey
          if (this.readonly) {
            return {
              key,
              value,
              editable: false,
            }
          }
          if (['projectName', 'unitOfMeasurement', 'code'].includes(key)) {
            editable = false
          }
          if (
            [P, Q].includes(v.projectName)
          ) {
            editable = false
            if (['oneYear', 'twoYear', 'threeYear', 'fourYear', 'fiveYear'].includes(key)) {
              calculable = true
              calculationKey = v.projectName + key
            }
          }
          return {
            key,
            value,
            editable,
            calculable,
            calculationKey,
          }
        })
        return {
          uuid: uuid(),
          data: data,
          informant: {
            personInCharge: v.personInCharge,
            informer: v.informer,
            telephone: v.telephone,
            fillInDate: v.fillInDate,
          }
        }
      })
    },
    getCalc (row, prop, value) {
      const calc = this.calc
      // 单位产品综合能耗进度节能量目标完成率 3
      // 产值综合能耗进度节能量目标完成率 4
      let key = ''
      if (row === 3) {
        key = P + prop
      } else if (row === 4) {
        key = Q + prop
      } else {
        return value
      }
      return typeof calc[key] === 'undefined' ? value : String(calc[key] || '')
    },
    // 初始化表数据
    initLists (params) {
      // 查询企业填报的数据
      if (this.loadList) {
        params = params || {
          [TABLE_FIELD_YEAR]: this.year,
          [TABLE_FIELD_QUARTER]: this.quarter,
          tenantId: this.enterpriseId
        }
        return this.loadList(params).then(async res => {
          if (res.code === 200) {
            const data = res.data || []
            if (data.length === 0) {
              const projects = [
                { projectName: '进度节能量目标', unitOfMeasurement: '吨标准煤', code: '01' },
                { projectName: '单位产品综合能耗实际完成进度节能量', unitOfMeasurement: '吨标准煤', code: '02' },
                { projectName: '产值综合能耗实际完成进度节能量', unitOfMeasurement: '吨标准煤', code: '03' },
                {
                  projectName: '单位产品综合能耗进度节能量目标完成率',
                  unitOfMeasurement: '%',
                  code: '04',
                },
                {
                  projectName: '产值综合能耗进度节能量目标完成率',
                  unitOfMeasurement: '%',
                  code: '05',
                },
              ]
              this.lists = this.transfer(projects)
            } else {
              const findIndex = data.findIndex(v => v.projectName === R)
              console.log('findIndex: ', findIndex)
              if (findIndex > -1) {
                // 进度节能量目标完成情况说明 (存取字段为 oneYear)
                const item = data.splice(findIndex, 1)[0]
                this.description = {
                  key: 'oneYear',
                  value: item.oneYear,
                  editable: !this.readonly
                }
              }
              this.lists = this.transfer(data)
            }

            this.$nextTick(() => {
              this.initInputIndex()
            })
          }
        }).catch(() => {
          this.$nextTick(() => {
            this.initInputIndex()
          })
        })
      }
    },
  },
}
</script>

<template>
  <div class="bg-white height-100 quarterly-account-table position-relative overflow-hidden">
    <slot name="title" :title="title" :series-no="seriesNo">
      <h2 class="table-title">
        {{title}}
      </h2>
    </slot>
    <div class="report-table-head">
      <table class="report-table">
        <table-head :columns="columns" :show-line-number="false"></table-head>
      </table>
    </div>
    <el-scrollbar :style="{height: 'calc(100% - 95px)'}" wrap-style="overflow-x: hidden;">
      <table class="report-table">
        <tbody ref="tbody">
        <tr v-for="item in lists" :key="item.uuid">
          <td
            v-for="(d, index) in item.data" :key="item.uuid + index"
            :class="{
              'is-calculable': d.calculable && d.calculationKey,
            }"
          >
            <div v-if="!d.editable" class="span-cell">
              {{
                (d.calculable && d.calculationKey)
                  ? calc[d.calculationKey]
                  : d.value
              }}
            </div>
            <div v-else class="input-cell">
              <input type="text" v-model="d.value" @click="clickHandler">
            </div>
          </td>
        </tr>
        <tr>
          <td colspan="3">
            <div class="span-cell big-td">
              进度节能量目标完成情况说明
            </div>
          </td>
          <td colspan="5">
            <div v-if="!description.editable" class="span-cell">
              {{description.value}}
            </div>
            <div v-else class="input-cell">
              <input type="text" :readonly="readonly" v-model="description.value" @click="clickHandler">
            </div>
          </td>
        </tr>
        </tbody>
      </table>
      <report-person ref="reportPerson" :informer="informant" :readonly="readonly"></report-person>
      <div v-if="tableDescription" class="fill-description">
        <template>
          <!-- <p>说明：</p>
          <p>1．本表进度节能量目标指节能主管部门根据“十二五”节能量目标和时间进度要求核定的进度节能量目标。</p>
          <p>2．实际完成节能量指2011年至本年度累计完成节能量；各年节能量按年度环比计算。</p>
          <p>3．进度节能量目标完成率=（实际完成节能量÷进度节能量目标）×100%。</p>
          <p>4．对进度节能量目标完成情况给予说明，字数应在100个汉字以内。</p> -->
          <el-input type="textarea" class="width-100 table-description" :value="tableDescription" readonly autosize></el-input>
        </template>
      </div>
    </el-scrollbar>
  </div>
</template>

<style scoped>
.report-table ::v-deep tr th:first-child,
.report-table ::v-deep tr td:first-child {
  width: 360px;
}
</style>
